package com.ling.pl.autoproject.definition.controller;

import com.ling.pl.autoproject.definition.model.ProjectEntity;
import com.ling.pl.autoproject.definition.model.ProjectVO;
import com.ling.pl.autoproject.definition.service.ProjectService;
import com.ling.pl.core.commons.support.DaoPage;
import com.ling.pl.core.commons.utils.AssertHelper;
import com.ling.pl.core.commons.utils.PageUtils;
import com.ling.pl.core.commons.utils.reflect.ReflectUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author bo.wang
 */
public class BaseProjectController {
    @Resource
    ProjectService projectService;

    public DaoPage loadProjectPage(Map parameter, Integer pageIndex,
                                   Integer pageSize) throws Exception {
        DaoPage daoPage = projectService.findProjectByParams(parameter, pageIndex, pageSize);
        return daoPage;
    }

    public Collection<ProjectVO> loadProjectList(Map parameter) throws Exception {
        List result = projectService.findProjectByParams(parameter);
        return result;
    }

    public ProjectVO loadAddProject(Map parameter) throws Exception {
        ProjectVO vo = new ProjectVO();
        return vo;
    }

    public ProjectVO loadModifyProject(Map parameter) throws Exception {
        Object id = parameter.get("id");
        return loadModifyProject(id);
    }

    public ProjectVO loadModifyProject(Object id) throws Exception {
        AssertHelper.notEmpty_assert(id, "编辑的主键不能为空");
        ProjectEntity entity = (ProjectEntity) projectService.get(ProjectEntity.class, id.toString());
        ProjectVO vo = projectService.convertProjectToVO(entity);
        return vo;
    }

    public void saveProject(Collection<ProjectVO> objs) throws Exception {
        Map results = PageUtils.assembleDatasetMap(objs);
        projectService.saveProjectDataListsMap(results);
    }

    public void saveAddProject(ProjectVO vo) throws Exception {
        ProjectEntity entity = projectService.convertProjectVOToEntity(vo);
        if (entity.getId() == null) {
            projectService.save(entity);
        } else {
            projectService.update(entity);
        }
        vo.setId(entity.getId());
    }

    public void updateModifyProject(ProjectVO vo) throws Exception {
        ProjectEntity entity = (ProjectEntity) projectService.get(ProjectEntity.class, vo.getId());
        ReflectUtils.copyProperties(vo, entity);
        projectService.update(entity);
    }
}

